import { Login } from '@/api/api';
import { ElLoading, ElMessage } from 'element-plus'
import {useStore} from '@/states/login'


export const login = (data) => {

  // 状态管理器实例化
  const store  = useStore()
  
  data.loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  Login(
    data.userinfo
    ).then(res => {
    data.userinfo = res._rawValue
    console.log(data.userinfo.userinfo)
    if (data.userinfo.userinfo){
      localStorage.setItem('user-info',JSON.stringify(data.userinfo.userinfo))
      store.restoreFromLocalStorage()
      data.loading.close()
      ElMessage({
        message: data.userinfo.message,
        type: 'success',
        duration: 1000,
        center: true,
      })
      routers.push({
        path: '/'
      })         
      return
    }
    data.loading.close()
    ElMessage({
      message: '账号密码错误！',
      type: 'error',
      duration: 1000,
      center: true,
    })
  })
  .catch(error => {
    console.log('error:', error);
    data.loading.close()
  })
}